package com.bobmccune.repository.jpa;

import com.bobmccune.model.User;
import com.bobmccune.repository.ContactRepository;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * JPA-based implementation of ContactRepository
 *
 * @author Bob McCune
 */
@Repository
public class ContactRepositoryJpa implements ContactRepository {

    @PersistenceContext
    private EntityManager em;

    protected EntityManager getEntityManager() {
        if (em == null) {
            throw new IllegalStateException("EntityManager has not been set.");
        }
        return em;
    }

    public User findById(Long id, boolean lock) {
        User contact;
        if (lock) {
            contact = getEntityManager().find(User.class, id);
            em.lock(contact, javax.persistence.LockModeType.WRITE);
        } else {
            contact = getEntityManager().find(User.class, id);
        }
        return contact;
    }

    @SuppressWarnings("unchecked")
    public List<User> findAll() {
        Query query = getEntityManager().createQuery("select c from User c");
        return query.getResultList();
    }

    public void save(User contact) {
        getEntityManager().persist(contact);
    }

    public User update(User contact) {
        return getEntityManager().merge(contact);
    }

    public void delete(User contact) {
        getEntityManager().remove(contact);
    }

    public void flush() {
        getEntityManager().flush();
    }

    public void clear() {
        getEntityManager().clear();
    }

}
